package com.dd.keel.core.framework.proxy;

import com.dd.keel.core.common.utils.ByteUtil;
import com.google.protobuf.ByteString;

/**
 * SOA proxy message util for sending and receiving
 * @author Kevin.XU
 *
 */
public class SoaProxyMsgMarshall {

	/**
	 * send soa proxy message
	 * @param conn
	 * @param request
	 * @throws Exception
	 */
	public static boolean sendRequest(ProxyConn conn, SoaProxyRequest request) throws Exception{
		SoaProxyMsg.soa_proxy_request.Builder builder = SoaProxyMsg.soa_proxy_request.newBuilder();
		builder.setGroupName(request.getGroupName());
		builder.setServiceName(request.getServiceName());
		builder.setServiceVersion(request.getServiceVersion());
		builder.setRequest(ByteString.copyFrom(request.getRequestBytes()));
		SoaProxyMsg.soa_proxy_request result = builder.build();
		if(result==null){
			return false;
		}
		byte[] body = result.toByteArray();
		byte[] header = new byte[4];
		ByteUtil.long2fourbyte(body.length, header, 0);
		conn.send(header, 0, 4);
		conn.send(body, 0, body.length);
		return true;
	}
	
	/**
	 * receive soa proxy message
	 * @param conn
	 * @return
	 * @throws Exception
	 */
	public static SoaProxyResponse receiveResponse(ProxyConn conn) throws Exception{
		byte[] header = new byte[4];
		conn.receive(header, 4);
		long len = ByteUtil.fourbyte2long(header, 0);
		byte[] body = new byte[(int)len];
		conn.receive(body, (int)len);
		SoaProxyMsg.soa_proxy_response response = SoaProxyMsg.soa_proxy_response.parseFrom(body);
		if(response==null){
			throw new Exception("parse response failed");
		}
		SoaProxyResponse result = new SoaProxyResponse();
		result.setStatus(response.getStatus());
		result.setResponseBytes(response.getResponse().toByteArray());
		return result;
	}
	
}
